//
//  SingleMeetingViewController.swift
//  TestMeeting
//
//  Created by json on 2020/12/28.
//

import UIKit
import WebRTC
import SwiftSignalRClient
import TangramKit

class SingleMeetingViewController: MyViewController {

    private var localView: RTCMTLVideoView?
    private var remoteView: RTCMTLVideoView?
    private var webRTCClient: WebRTCClient?
    private var signalConnection: HubConnection?
    private let config = Config.default
    private var label: UILabel?
    private var connectL: UILabel?
    private var hasRemoteL: UILabel?
    private var textField: UITextField?
    private var ices: [RTCIceCandidate] = []
    private var role: Int = 0 /// 创建
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Single Meeting"
        
        self.rootLayout?.tg_insetsPaddingFromSafeArea = UIRectEdge.all
        
        self.initSubView()
        
        webRTCClient = WebRTCClient(iceServers: self.config.webRTCIceServers)
        webRTCClient?.delegate = self
        self.signalConnection = HubConnectionBuilder(url: URL(string: "http://192.168.101.11:14612/signalling")!)
            .withLogging(minLogLevel: .debug)
            .withAutoReconnect()
            .withHubConnectionDelegate(delegate: self)
            .build()
        self.signalConnection?.start()
        self.signalConnection?.on(method: "JoinSession", callback: { (data: SingalResult) in
            print("有用户加入房间 \(data.result)")
        })
        self.signalConnection?.on(method: "ExitRoom", callback: { (data: SingalResult) in
            print("有用户退出房间,房主退出不会造成房间关闭 \(data.result)")
        })
        self.signalConnection?.on(method: "CloseRoom", callback: { (data: SingalResult) in
            print("关闭房间,由房主关闭或没人自动关闭 \(data.result)")
        })
        self.signalConnection?.on(method: "addIceCandidate", callback: { (data: SingalResult2) in
            print("addIceCandidate:")
            let ice = RTCIceCandidate(sdp: data.result.candidate, sdpMLineIndex: Int32(data.result.sdpMLineIndex), sdpMid: data.result.sdpMid)
            self.webRTCClient?.set(remoteCandidate: ice)
        })
        self.signalConnection?.on(method: "RemoveIceCandidate", callback: { (data: SingalResult) in
            print("RemoveIceCandidate: \(data.result)")
        })
        self.signalConnection?.on(method: "Answer", callback: { (data: SingalResult) in
            print("Answerwwwwwww \(data.result)")
            
            if self.role == 1 {
                let sdp = RTCSessionDescription(type: RTCSdpType.offer, sdp: data.result)
                self.webRTCClient?.set(remoteSdp: sdp, completion: { (error: Error?) in
                    print("Local Peer Remote Description set: " + error.debugDescription)
                    self.webRTCClient?.answer(completion: { (newsdp) in
                        self.signalConnection?.invoke(method: "Answer",newsdp.sdp , invocationDidComplete: { (error: Error?) in
                            print("answer erro: \(error?.localizedDescription ?? "default error")")
                        })
                        self.webRTCClient?.renderRemoteVideo(to: self.remoteView!)
                    })
                })
                
            }else {
                let sdp = RTCSessionDescription(type: RTCSdpType.answer, sdp: data.result)
                self.webRTCClient?.set(remoteSdp: sdp, completion: { (error: Error?) in
                    print("Local Peer Remote Description set: " + error.debugDescription)
                    
                    self.webRTCClient?.renderRemoteVideo(to: self.remoteView!)
                })
            }
            
            
        })
        
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.textField?.resignFirstResponder()
    }

    @objc func createHandle()  {
        let text = self.textField?.text ?? ""
        if text.count > 0 {
            self.role = 1;
            self.signalConnection?.invoke(method: "JoinSession", text, invocationDidComplete: { (error: Error?) in
                
            })
            
            
        }else{
            self.signalConnection?.invoke(method: "CreateSession", 3, resultType: SingalResult.self, invocationDidComplete: { (result: SingalResult?, error: Error?) in
                print("房间号\(String(describing: result?.result))")
                DispatchQueue.main.async {
                    self.label?.text = result?.result
                }
                if result?.result == nil {
                    print("创建房间失败")
                    return
                }
                self.webRTCClient?.offer(completion: { (sdp) in
                    self.signalConnection?.invoke(method: "Answer",sdp.sdp , invocationDidComplete: { (error: Error?) in
                        print("answer erro: \(error?.localizedDescription ?? "default error")")
                    })
                })
            })

        }
        self.webRTCClient?.startCaptureLocalVideo(renderer: self.localView!)
    }
    @objc func closeHandle()  {
        
    }
    @objc func exitHandle()  {
        self.signalConnection?.stop()
//        self.webRTCClient
    }
    
    
    func initSubView() {
        self.rootLayout?.tg_padding = UIEdgeInsets.init(top: 10, left: 20, bottom: 0, right: 20)
        let bottomActionLayout = TGLinearLayout(TGOrientation.horz)
        bottomActionLayout.tg_left.equal(0)
        bottomActionLayout.tg_bottom.equal(0)
        bottomActionLayout.tg_right.equal(0)
        bottomActionLayout.tg_height ~= 50
        self.rootLayout?.addSubview(bottomActionLayout)
        
        let createBtn = UIButton(type: UIButton.ButtonType.custom)
        createBtn.setTitle("Create and Join", for: UIControl.State.normal)
        createBtn.tg_height.equal(bottomActionLayout.tg_height)
        createBtn.tg_width.equal(100%)
        
        let closeBtn = UIButton(type: UIButton.ButtonType.custom)
        closeBtn.setTitle("Close", for: UIControl.State.normal)
        closeBtn.tg_height.equal(bottomActionLayout.tg_height)
        closeBtn.tg_width.equal(50%)
        
        let exitBtn = UIButton(type: UIButton.ButtonType.custom)
        exitBtn.setTitle("Exit", for: UIControl.State.normal)
        exitBtn.tg_height.equal(bottomActionLayout.tg_height)
        exitBtn.tg_width.equal(50%)
        
        bottomActionLayout.addSubview(createBtn)
        bottomActionLayout.addSubview(closeBtn)
        bottomActionLayout.addSubview(exitBtn)
        
        textField = UITextField()
        textField?.tg_horzMargin(0)
        textField?.tg_height.equal(50)
        textField?.placeholder = "输入房间号"
        textField?.backgroundColor = UIColor.white.withAlphaComponent(0.2)
        textField?.layer.cornerRadius = 6
        textField?.layer.masksToBounds = true
        self.rootLayout?.addSubview(textField!)
        
        localView = RTCMTLVideoView()
        localView?.tg_left.equal(textField?.tg_left)
        localView?.tg_top.equal(textField?.tg_bottom, offset: 8)
        localView?.tg_width.equal(50%, increment: -10)
        localView?.tg_height.equal(localView?.tg_width, increment: 0, multiple: 1.78)
        localView?.backgroundColor = UIColor.white.withAlphaComponent(0.2)
        localView?.layer.cornerRadius = 6
        localView?.layer.masksToBounds = true
    
        
        remoteView = RTCMTLVideoView()
        remoteView?.tg_left.equal(localView?.tg_right, offset: 20)
        remoteView?.tg_top.equal(textField?.tg_bottom, offset: 8)
        remoteView?.tg_width.equal(50%, increment: -10)
        remoteView?.tg_height.equal(remoteView?.tg_width, increment: 0, multiple: 1.78)
        remoteView?.backgroundColor = UIColor.white.withAlphaComponent(0.2)
        remoteView?.layer.cornerRadius = 6
        remoteView?.layer.masksToBounds = true
        
        self.rootLayout?.addSubview(localView!)
        self.rootLayout?.addSubview(remoteView!)
        
        createBtn.addTarget(self, action: #selector(createHandle), for: UIControl.Event.touchUpInside)
        closeBtn.addTarget(self, action: #selector(closeHandle), for: UIControl.Event.touchUpInside)
        exitBtn.addTarget(self, action: #selector(exitHandle), for: UIControl.Event.touchUpInside)
        
        label = UILabel()
        label?.tg_left.equal(self.localView?.tg_left)
        label?.tg_top.equal(self.localView?.tg_bottom, offset: 20)
        label?.tg_size(width: TGLayoutSize.wrap, height: TGLayoutSize.wrap)
        self.rootLayout?.addSubview(label!)
        
        connectL = UILabel()
        connectL?.tg_left.equal(self.localView?.tg_left)
        connectL?.tg_top.equal(self.label?.tg_bottom, offset: 12)
        connectL?.tg_size(width: TGLayoutSize.wrap, height: TGLayoutSize.wrap)
        connectL?.text = "未连接"
        self.rootLayout?.addSubview(connectL!)
        
        hasRemoteL = UILabel()
        hasRemoteL?.tg_left.equal(self.localView?.tg_left)
        hasRemoteL?.tg_top.equal(self.connectL?.tg_bottom, offset: 12)
        hasRemoteL?.tg_size(width: TGLayoutSize.wrap, height: TGLayoutSize.wrap)
        hasRemoteL?.text = "no"
        self.rootLayout?.addSubview(hasRemoteL!)
    }
}


extension SingleMeetingViewController : WebRTCClientDelegate {
    
    func webRTCClient(_ client: WebRTCClient, didDiscoverLocalCandidate candidate: RTCIceCandidate) {
        var ice = Ice()
        ice.candidate = candidate.sdp;
        ice.sdpMLineIndex = Int(candidate.sdpMLineIndex);
        ice.sdpMid = candidate.sdpMid ?? ""
        self.signalConnection?.invoke(method: "AddIceCandidate", ice, invocationDidComplete: { (erro: Error?) in
            print("aaaaa: \(erro.debugDescription)")
        })
        print("didDiscoverLocalCandidate")
    }
    
    func webRTCClient(_ client: WebRTCClient, didChangeConnectionState state: RTCIceConnectionState) {
        print("didChangeConnectionState")
    }
    
    func webRTCClient(_ client: WebRTCClient, didReceiveData data: Data) {
        print("didReceiveData")
    }
    
    
}
extension SingleMeetingViewController: HubConnectionDelegate {
    func connectionDidOpen(hubConnection: HubConnection) {
        print("connectionDidOpen")
        self.connectL?.text = "已连接"
        self.connectL?.textColor = UIColor.green
    }
    
    func connectionDidFailToOpen(error: Error) {
        print("connectionDidFailToOpen \(error.localizedDescription)")
        self.connectL?.text = "连接失败"
        self.connectL?.textColor = UIColor.red
    }
    
    func connectionDidClose(error: Error?) {
        print("connectionDidClose \(String(describing: error?.localizedDescription))")
        self.connectL?.text = "已关闭"
        self.connectL?.textColor = UIColor.red
    }
    
    
}
